package controllers

import (
	"encoding/json"
	"github.com/beego/beego/v2/adapter/validation"
	beego "github.com/beego/beego/v2/server/web"
	"shop/models"
	"strconv"
)

type AnchorController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 主播添加
func (c *AnchorController) Add() {
	name := c.GetString("name")
	sex := c.GetString("sex")
	cate := c.GetString("cate")
	intro := c.GetString("intro")
	img := c.GetString("img")
	fans, _ := c.GetInt("fans")
	anchor := models.Anchor{
		Name:  name,
		Sex:   sex,
		Cate:  cate,
		Intro: intro,
		Img:   img,
		Fans:  fans,
	}
	valid := validation.Validation{} //beego  自带的验证器 （过滤器）
	validation.SetDefaultMessage(map[string]string{
		"Required": "数据不能为空",
	})
	_, err := valid.Valid(&anchor)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "验证错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if valid.HasErrors() {
		for _, err = range valid.Errors {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  err.Error(),
				Data: nil,
			}
			c.ServeJSON()
		}
		return
	}

	//入库之前做数据验证
	err = models.DB.Create(&anchor).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

// 主播列表
func (c *AnchorController) List() {
	page, _ := c.GetInt("page", 1) //接收当前页
	size, _ := c.GetInt("size", 5) //接收每页条数
	key := "list-" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()
	//判断缓存中是否有数据，有直接返回，没有在查询数据库，并且存入数据库
	pageData := make(map[string]interface{}) //容器
	if err != nil {
		//查数据库
		var count int64
		err = models.DB.Model(&models.Anchor{}).Count(&count).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "总查询失败",
			}
			c.ServeJSON()
			return
		}
		var anchor []models.Anchor //切片
		offset := (page - 1) * size
		err = models.DB.Debug().Model(&models.Anchor{}).Limit(size).Offset(offset).Find(&anchor).Error //核心
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "查询失败",
			}
			c.ServeJSON()
			return
		}

		pageData["count"] = count   //总条数
		pageData["anchor"] = anchor //主播数据

		jsonByte, _ := json.Marshal(&pageData)
		value := string(jsonByte)
		models.Rdb.Set(key, value, 0)

		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-mysql",
			Data: pageData,
		}
		c.ServeJSON()
	} else {
		//返回缓存
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}

}

// 主播删除
func (c *AnchorController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Anchor{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

// 主播详情
func (c *AnchorController) Info() {
	id, _ := c.GetInt("id") //key  value
	key := "anchor-" + strconv.Itoa(id)
	//判断缓存中是否有数据，有的话直接读取缓存，没有的话查询数据库，并且存入缓存(原理)
	val, err := models.Rdb.Get(key).Result() //获取缓存
	var anchor models.Anchor
	if err != nil {
		//查询数据库
		err = models.DB.Where("id=?", id).First(&anchor).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "详情展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		//存入缓存
		jsonByte, _ := json.Marshal(anchor)
		value := string(jsonByte)
		models.Rdb.Set(key, value, 0)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "详细查询成功-mysql",
			Data: anchor,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &anchor)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "详情查询成功过-redis",
			Data: anchor,
		}
		c.ServeJSON()
	}

	/*var anchor models.Anchor
	err := models.DB.Model(&models.Anchor{}).Where("id=?", id).First(&anchor).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "详情查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "详情查询成功",
			Data: anchor,
		}
		c.ServeJSON()
	}*/
}

func (c *AnchorController) Update() {
	name := c.GetString("name")
	sex := c.GetString("sex")
	cate := c.GetString("cate")
	intro := c.GetString("intro")
	img := c.GetString("img")
	fans, _ := c.GetInt("fans")
	id, _ := c.GetInt("id")

	var anchor = models.Anchor{
		Name:  name,
		Sex:   sex,
		Cate:  cate,
		Intro: intro,
		Img:   img,
		Fans:  fans,
	}
	err := models.DB.Where("ID=?", id).Updates(&anchor).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: anchor,
		}
		c.ServeJSON()
	}
}
